
import pymysql

class MySQLHelper(object):
	def __init__(self,
	             db,
	             host="localhost",
	             port = 3306,
	             user = "root",
	             password = "",
	             charset = "utf8"
	             ):
		
		self.conn = pymysql.Connect(
			db = db,
			host="localhost",
			port=3306,
			user="root",
			passwd="",
			charset="utf8"
		)
		
		self.cursor = self.conn.cursor()
	
	def __del__(self):
		self.cursor.close()
		self.conn.close()
	
	def findAll(self, sql):
		
		self.cursor.execute(sql)
		
		fa = self.cursor.fetchall()
		
		return fa
	
	def add(self, sql):
		try:
			self.cursor.execute(sql)
		except Exception as me:
			print(me)
			self.conn.rollback()
			return -1
		else:
			self.conn.commit()
			return 0
	
	def remove(self, sql):
		"""
		执行数据库的删除操作
		
		:param sql: 传输删除用的sql语句
		:return:
			-1:失败
			0 ：成功
		"""
		
		try:
			self.cursor.execute(sql)
		except Exception as me:
			print(me)
			self.conn.rollback()
			return -1
		else :
			self.conn.commit()
			return 0
		
	def modify(self, sql):
		try:
			self.cursor.execute(sql)
		except Exception as me:
			print(me)
			self.conn.rollback()
			return -1
		else :
			self.conn.commit()
			return 0
		
		

		
	def show(self, f):
		
		mstr = """ {uid}---{uname}---{upwd}""".format(
			uid = f[0],
			uname=f[1],
			upwd=f[2],
		)
		
		return mstr


if __name__ == '__main__':
	mh = MySQLHelper("taobao")
	
	mh.add("insert into user(uname, upassword) values('{un}', '{up}');".format(
		un="Lucy",
		up="123"
	))
	
	fa = mh.findAll("select * from user;")
	
	for f in fa:
		print(mh.show(f))
	
	# ret = mh.remove("delete from user where uid = 11;")
	# if ret == 0:
	# 	pass
	
	mh.modify("update user set upassword = '456' where uid = {dd}".format(
		dd = 13
	))
	
	fa = mh.findAll("select * from user;")
	
	for f in fa:
		print(mh.show(f))
